package com.linln.admin.config;

import net.sf.ehcache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;

/**
 * Spring缓存配置类
 * @author 小懒虫
 * @date 2024/11/04
 */
@Configuration
@EnableCaching
public class CacheConfig {

    /**
     * EhCache缓存管理器工厂Bean
     */
    @Bean
    public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
        EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean();
        cacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
        cacheManagerFactoryBean.setShared(true);
        return cacheManagerFactoryBean;
    }

    /**
     * EhCache原生CacheManager
     * ehCacheManagerFactoryBean()会创建一个CacheManager，所以不需要再通过下面的方法创建CacheManager
     */
    // @Bean
    // public CacheManager cacheManager(EhCacheManagerFactoryBean ehCacheManagerFactoryBean) {
    //     return ehCacheManagerFactoryBean.getObject();
    // }

    /**
     * Spring Cache管理器（用于@Cacheable注解）
     */
    @Bean
    public org.springframework.cache.CacheManager springCacheManager(CacheManager cacheManager) {
        return new EhCacheCacheManager(cacheManager);
    }
}